package cn.wzvtcsoft.sys.security;

import cn.wzvtcsoft.sys.entity.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Objects;

/**
 * @author swxu_2005@163.com
 * 为什么不继承User，因为User属性中有些是hibernate懒加载的，用BeanUtils.copyProperties拷贝后失效了
 * 密码：$2a$10$mqujYlxdiOGaDfJGGNDv/uVT.DYxsyqSca4W4JJIz3NvWWxRA9Mlu
 */
public class BosUserDetails implements UserDetails {

  private User user;

  public BosUserDetails(User user) {
    this.user = user;
  }

  public User getUser() {
    return user;
  }

  @Override
  public String getUsername() {
    return user.getNumber();
  }

  @Override
  public String getPassword() {
    return user.getPassword();
  }

  @Override
  public Collection<? extends GrantedAuthority> getAuthorities() {
    return new ArrayList<>();
  }

  @Override
  public boolean isAccountNonExpired() {
    return true;
  }

  @Override
  public boolean isAccountNonLocked() {
    return true;
  }

  @Override
  public boolean isCredentialsNonExpired() {
    return true;
  }

  @Override
  public boolean isEnabled() {
    return user.getState() == 1;
  }

  /**
   * !!! 必须重写equals和hashCode方法，因为在踢用户时是根据UserDetails来比对登陆用户
   */
  @Override
  public boolean equals(Object o) {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }
    BosUserDetails that = (BosUserDetails) o;
    return Objects.equals(user, that.user);
  }

  @Override
  public int hashCode() {
    return Objects.hash(user);
  }
}
